<?php

namespace app\store\controller\ditui;

use app\store\controller\Controller;
use app\store\model\Store as StoreModel;
use think\Db;

class Dtzhuanhua extends Controller
{
    public function zhuanhua()
    {
        $paramArr = $this->request->param();
        $formInline = isset($paramArr['formInline']) ? $paramArr['formInline'] : "";
        $currentPage = isset($paramArr['currentPage']) ? $paramArr['currentPage'] : 1;
        $pageSize = isset($paramArr['pageSize']) ? $paramArr['pageSize'] : $this->SIZE30;
        $limit = " limit ".($currentPage-1)*$pageSize.", ".$pageSize;

        $order = " order by aa.dl_id desc";
        $where = " where aa.dl_shopid=".$this->ad_shopid." ";

        //不同用户权限，查看分配给自己的专属班级，查看分配给自己的任务数据，是否只能查看自己的数据。0：表示查看所有数据，1：表示只查看分配给自己的数据
        $showMyData = $this->store['user']['show_calladmin'];
        $showMyData==10 ? $where .= " and du_sayadmid=".$this->admin_id : "";

        //$where = " where aa.dl_shopid=".$this->ad_shopid." and aa.du_flowid!=80 ";  //不展示已成交的数据
        // 统计当前时间到5天后的时间为急需回访的数据
        $nextCallBackDay = date('Y-m-d', strtotime('5 day'));
        $backCallwhere = " and aa.du_nextcall >= '".date('Y-m-d H:i:s',time())."' and aa.du_nextcall <= '".$nextCallBackDay.' 23:59:59'."'";

        $begTimeStr = "";
        $endTimeStr = "";
        if($formInline!=""){
            trim($formInline['startTime'])!="" ? $where .= " and aa.dl_addtime >= '".trim($formInline['startTime'])."'" : "";
            trim($formInline['endTime'])!="" ? $where .= " and aa.dl_addtime <= '".trim($formInline['endTime'])."'" : "";
            trim($formInline['phone'])!="" ? $where .= " and aa.du_mobile like '%".$formInline['phone']."%'" : "";
            trim($formInline['school'])!="" ? $where .= " and aa.du_school like '%".$formInline['school']."%'" : "";
            trim($formInline['name'])!="" ? $where .= " and aa.du_truename like '%".$formInline['name']."%'" : "";
            trim($formInline['remark'])!="" ? $where .= " and aa.du_zhmyremark like '%".$formInline['remark']."%'" : "";
//            trim($formInline['remark'])!="" ? $where .= " and aa.du_zhremarkstr like '%".json_encode($formInline['remark'])."%'" : "";
            trim($formInline['xuehao'])!="" ? $where .= " and aa.dl_userid =".$formInline['xuehao'] : "";
            trim($formInline['sex'])!="" ? $where .= " and aa.du_sex =".$formInline['sex'] : "";
            trim($formInline['sellerId'])!="" ? $where .= " and aa.dl_dituiuid =".$formInline['sellerId'] : "";
            trim($formInline['sayadminId'])!="" ? $where .= " and aa.du_sayadmid =".$formInline['sayadminId'] : "";
            trim($formInline['channelStr'])!="" ? $where .= " and aa.dl_channel ='".$formInline['channelStr']."'" : "";
            // 查找今天昨天数据
            $day_str = trim($formInline['day_str']);
            if($day_str=='today'){
                $today = date('Y-m-d');
                $begTimeStr = $today.' 00:00:00';
                $endTimeStr = $today. ' 23:59:59';
                $where .= " and dl_addtime >= '".$begTimeStr."'";
                $where .= " and dl_addtime <= '".$endTimeStr."'";
            }
            if($day_str=='yesterday'){
                // 获取昨天的日期时间对象
                $yesterday = date('Y-m-d', strtotime('-1 day'));
                $begTimeStr = $yesterday.' 00:00:00';
                $endTimeStr = $yesterday. ' 23:59:59';
                $where .= " and dl_addtime >= '".$begTimeStr."'";
                $where .= " and dl_addtime <= '".$endTimeStr."'";
            }
            // 各个流程
            $flowint = trim($formInline['flowint']);
            if($flowint!=""){
                if($flowint=='all'){
                    $where .= " and aa.du_flowid > -2 ";
                }
                // 统计最近5天需要的回访为回访列表
                else if($flowint=='back'){
                    $where .= $backCallwhere;
                    $order = " order by aa.du_nextcall desc ";
                }
                else{
                    $where .= " and aa.du_flowid = ".$flowint;
                }
            }
        }
        //ddd($where);
        //$sql = "select * from ".getTable('ditui_user').$where.$order.$limit;
        $sqlHeader0 = "select * from ";
        $sqlHeader = getTable('ditui_user')." as aa left join ".getTable('user')." as bb on aa.dl_userid=bb.user_id ";
        $sql = $sqlHeader0.$sqlHeader.$where.$order.$limit;
        //ddd($sql);
        $list = Db::query($sql);

        //当前查询的总数量，传递总数用于分页
        //$sqlNum = "select count(*) as allNum from ".getTable('ditui_user').$where;
        $sqlNum = "select count(*) as allNum from ".$sqlHeader.$where;
        $allNumArr = Db::query($sqlNum);
        //当前查询的回访人数
        $backCallNum = "select count(*) as allNum from ".getTable('ditui_user')." as aa where aa.dl_shopid=".$this->ad_shopid." ".$backCallwhere;
        //ddd($backCallNum);
        $backCallNumArr = Db::query($backCallNum);

        // 初始化页面获取数据字典数据
        //var flowArr = ['all','back',0,1,2,3,4,5,6,80,-1];  //组装转发标签卡
        $bbb = $this->getZDarr();
        $allBigNumArr = $this->getPerAllNum($bbb['zhuanghuaArr'], $sqlHeader, $where);
        $allBigNumArr['allNum_all'] = $allNumArr[0]['allNum'];
        $allBigNumArr['allNum_back'] = $backCallNumArr[0]['allNum'];
        $back['allBigNumArr'] = $allBigNumArr;

        // 格式化备注数据展示为列
        foreach($list as $key => $vvv){
            if($vvv['du_zhremarkstr']!=''){
                $list[$key]['zhmarkArr'] = json_decode($vvv['du_zhremarkstr'], true);
            }
            else{
                $list[$key]['zhmarkArr'] = [];
            }
        }

        if ($this->request->isAjax()) {
            $back['list'] = $list;
            $back['begTimeStr'] = $begTimeStr;
            $back['endTimeStr'] = $endTimeStr;
            $back['allNum'] = $allNumArr[0]['allNum'];
            $back['callBackNum'] = $backCallNumArr[0]['allNum'];
            return $this->renderSuccess('数据请求成功', '', $back);
        }
        //首次非ajax请求，直接控制器推送数据
        else{
            // 获取所有地推专员数据信息
            $sellerArr = Db::name('ditui_seller')->where(['ds_shopid'=>$this->ad_shopid])->select()->toArray();
            $adminName = $this->admin_realname;
            // 获得所有管理员列表，用于做沟通咨询
            $adminArr = Db::name('store_user')->where(['ad_shopid'=>$this->ad_shopid])->select()->toArray();

            //ddd($sellerArr);
            return $this->fetch('ditui/zhuanhua', ['data' =>['allBigNumArr'=>$allBigNumArr, 'showMyData'=>$showMyData, 'adminName'=>$adminName, 'zhColorArr'=>$bbb['zhColorArr'], 'schoolArr'=>$bbb['schoolArr'], 'flowArr'=>$bbb['flowArr'], 'sellerArr'=>$sellerArr, 'adminArr'=>$adminArr, 'zhuanghuaArr'=>$bbb['zhuanghuaArr'], 'list'=>$list, 'allNum'=>$allNumArr[0]['allNum'], 'callBackNum'=>$backCallNumArr[0]['allNum'] ]]);
        }
    }
    /**获取字典相关的数组*/
    private function getZDarr(){
        $zidianObj = Db::name('ditui_zidian')->where('dz_shopid', $this->ad_shopid)->find();
        if(!$zidianObj){
            $zidianCC = new Dtzidian();
            $zhuanghuaArr = $zidianCC->getArr(1);
            $schoolArr = $zidianCC->getArr(3);
            $zhColorArr = $zidianCC->getArr(11);
        }
        else{
            $zhuanghuaArr = explode(',', $zidianObj['dz_zhtxtstr']);
            $schoolArr = explode(',', $zidianObj['dz_schoolstr']);
            $zhColorArr = explode(',', $zidianObj['dz_zhcolor']);
        }

        //var flowArr = ['all','back',0,1,2,3,4,5,6,80,-1];  //组装转发标签卡
        $flowArr[] = 'all';
        $flowArr[] = 'back';
        $flowArr[] = 0;
        foreach ($zhuanghuaArr as $kkk => $vvv){
            $flowArr[] = ($kkk+1);
        }
        $flowArr[] = 80;
        //$flowArr[] = 80; 不展示已成交的用户
        $flowArr[] = -1;

        $back['flowArr'] = $flowArr;
        $back['zhuanghuaArr'] = $zhuanghuaArr;
        $back['schoolArr'] = $schoolArr;
        $back['zhColorArr'] = $zhColorArr;
        return $back;
    }
    /**获取各个阶段的总数*/
    private function getPerAllNum($zhuanghuaArr, $sqlHeader, $where){
        $flowIdArr[] = 0;
        foreach ($zhuanghuaArr as $kkk => $vvv){
            $flowIdArr[] = $kkk+1;
        }
        $flowIdArr[] = 80;
        $flowIdArr[] = -1;

        // 根据转化流程id查找对应的数据个数
        $back = array();
        foreach ($flowIdArr as $v2){
            $flowInt = $v2; //从零开始的转化，包括陌客0，成交80，回收站-1；
            $sqlNum = "select count(*) as allNum from ".$sqlHeader.$where. " and aa.du_flowid=".$flowInt;
            //echo $sqlNum.'<br>';
            $allNumArr = Db::query($sqlNum);
            $back['allNum_'.$flowInt] = $allNumArr[0]['allNum'];
        }
        //ddd($back);
        return $back;
    }

    /** 手动添加备注*/
    public function addRemark(){
        $paramArr = $this->request->param();
        $nowdl_id = isset($paramArr['nowdl_id']) ? $paramArr['nowdl_id'] : 0;
        $remarkTxt = isset($paramArr['remarkTxt']) ? $paramArr['remarkTxt'] : "";

        $upArr['du_zhmyremark'] = $remarkTxt;
        Db::name('ditui_user')->where('dl_id',$nowdl_id)->update($upArr);

        $back['state'] = 'addOk';
        $back['msg'] = '备注成功';
        return $this->renderSuccess('添加成功', '', $back);
    }

    /** 手动添加陌客，修改陌客信息 */
    public function addmoke()
    {
        $paramArr = $this->request->param();
        $key = isset($paramArr['key']) ? $paramArr['key'] : "add";
        $nowdl_id = isset($paramArr['nowdl_id']) ? $paramArr['nowdl_id'] : 0;
        $personObj = isset($paramArr['personObj']) ? $paramArr['personObj'] : "";
        // 1. 查找此陌客在平台中是否已有数据
        $ptUobj = Db::name('user')->where(['true_mobile'=>$personObj['mmphone']])->find();
        // ddd($ptUobj);
        if($ptUobj){
            $inArr['dl_userid'] = $ptUobj['user_id'];
            $upArr['dl_userid'] = $ptUobj['user_id'];
        }
        //ddd($personObj);
        if($key=='add'){
            $userObj = Db::name('ditui_user')->where(['du_mobile'=>$personObj['mmphone'], 'dl_shopid'=>$this->ad_shopid])->find();
            if($userObj){
                return $this->renderError('该手机号已经添加过了');
            }
            $inArr['dl_shopid'] = $this->ad_shopid;
            $inArr['dl_shopname'] = $this->ad_shopname;
            $inArr['dl_activetitle'] = "手动添加";
            isset($personObj['dl_channel']) ? $inArr['dl_channel'] = $personObj['dl_channel'] : "";
            //$inArr['dl_dituiname'] = $this->admin_username.'（'.$this->admin_realname.'）';
            $inArr['dl_dituiname'] = '手录 ('.$this->admin_realname.')';
            $inArr['wxapp_id'] = $this->wxapp_id;
            $inArr['du_mobile'] = $personObj['mmphone'];
            $inArr['du_truename'] = $personObj['mokeName'];
            $inArr['du_sex'] = $personObj['sex'];
            $inArr['du_age'] = $personObj['age'];
            $inArr['du_ptruename'] = $personObj['pname'];
            $inArr['du_address'] = $personObj['address'];
            $inArr['du_school'] = $personObj['school'];
            $inArr['du_grade'] = $personObj['grade'];
            $inArr['du_dingjin'] = $personObj['du_dingjin'];
            $inArr['dl_dafen'] = $personObj['dafen'];
            $inArr['dl_addtime'] = date('Y-m-d H:i:s',time());
            //ddd($inArr);
            Db::name('ditui_user')->insert($inArr);

            $back['state'] = 'addOk';
            $back['msg'] = '添加成功';
            return $this->renderSuccess('添加成功', '', $back);
        }
        else{
            $upArr['du_mobile'] = $personObj['mmphone'];
            $upArr['du_truename'] = $personObj['mokeName'];
            isset($personObj['dl_channel']) ? $upArr['dl_channel'] = $personObj['dl_channel'] : "";
            $upArr['du_sex'] = $personObj['sex'];
            $upArr['du_age'] = $personObj['age'];
            $upArr['du_ptruename'] = $personObj['pname'];
            $upArr['du_address'] = $personObj['address'];
            $upArr['du_school'] = $personObj['school'];
            $upArr['du_grade'] = $personObj['grade'];
            $upArr['du_dingjin'] = $personObj['du_dingjin'];
            $upArr['dl_dafen'] = $personObj['dafen'];
            Db::name('ditui_user')->where('dl_id',$nowdl_id)->update($upArr);

            $back['state'] = 'addOk';
            $back['msg'] = '修改成功';
            return $this->renderSuccess('修改成功', '', $back);
        }
    }

    /** 批量设置用户状态 */
    public function flowRemove(){
        $paramArr = $this->request->param();
        $opmStr = isset($paramArr['opmStr']) ? $paramArr['opmStr'] : 'move';
        $nowFlowInt = isset($paramArr['nowFlowInt']) ? $paramArr['nowFlowInt'] : 0;
        $fenPeiId = isset($paramArr['fenpeiAdminId']) ? $paramArr['fenpeiAdminId'] : 0;
        $fenPeiName = isset($paramArr['fenpeiAdminName']) ? $paramArr['fenpeiAdminName'] : '';
        $backCallNextTime = isset($paramArr['backCallNextTime']) ? $paramArr['backCallNextTime'] : '';
        $shiTingTime = isset($paramArr['shiTingTime']) ? $paramArr['shiTingTime'] : '';
        $opmDlidArr = isset($paramArr['opmDlidArr']) ? $paramArr['opmDlidArr'] : "";
        if($opmDlidArr!=""){
            if($opmStr=='move'){
                $setSql = " set du_flowid=".$nowFlowInt;
            }
            if($opmStr=='fenpei'){
                $setSql = " set du_sayadmid=".$fenPeiId. ", du_sayname='$fenPeiName'";
            }
            if($opmStr=='backcall'){
                if($backCallNextTime!=''){
                    if(strtotime($backCallNextTime)<=time()){
                        return $this->renderError('回访时间必需大于当前时间');
                    }
                    $setSql = " set du_nextcall='".$backCallNextTime."' ";
                }
                //清空回访时间的设置
                else{
                    $setSql = " set du_nextcall=NULL ";
                }
            }
            if($opmStr=='shiting'){
                if($shiTingTime!=''){
                    if(strtotime($shiTingTime)<=time()){
                        return $this->renderError('上门试听时间必需大于当前时间');
                    }
                    $setSql = " set du_shiting='".$shiTingTime."' ";
                }
                //清空回访时间的设置
                else{
                    $setSql = " set du_shiting=NULL ";
                }
            }

            if(count($opmDlidArr)>0){
                $fruits_string = implode(', ', $opmDlidArr);
                $update = "update ".getTable('ditui_user'). $setSql. " where dl_id in (".$fruits_string.")";
                //ddd($update);
                Db::query($update);
                $back['state'] = 'addOk';
                $back['msg'] = '设置成功';
                $back['du_nextcall'] = $backCallNextTime;
                return $this->renderSuccess('设置成功', '', $back);
            }
        }
    }

    /** 添加沟通日志 */
    public function addcalllog(){
        $paramArr = $this->request->param();
        $logFormObj = isset($paramArr['logFormObj']) ? $paramArr['logFormObj'] : '';
        $nowdl_id = isset($paramArr['nowdl_id']) ? $paramArr['nowdl_id'] : 0;

        $inArr['cl_dlid'] = $nowdl_id;
        $inArr['cl_shopid'] = $this->ad_shopid;
        $inArr['cl_shopname'] = $this->ad_shopname;
        $inArr['cl_typestr'] = $logFormObj['opmstr'];
        $inArr['cl_adminid'] = $this->admin_id;
        $inArr['cl_adminname'] = $this->admin_realname;
        $inArr['cl_logtxt'] = $logFormObj['logtxt'];
        $inArr['wxapp_id'] = $this->wxapp_id;
        $inArr['cl_addtime'] = date('Y-m-d H:i:s',time());
        //ddd($inArr);
        Db::name('ditui_calllog')->insert($inArr);

        //冗余inline_user表中的日志数据
        //查找所有的日志
        $logList = Db::name('ditui_calllog')->whereIn('cl_dlid', $nowdl_id)->order(['cl_id'=>'desc'])->select()->toArray();
        $len = count($logList);
        $logToMyRemarkStr = "";
        foreach($logList as $kkk => $vvv){
            $logList[$kkk]['no'] = $len;
            $logToMyRemarkStr .= $vvv['cl_logtxt']."@@@";
            $len--;
        }
        $upArr['du_call_admid'] = $this->admin_id;
        $upArr['du_call_admtruename'] = $this->admin_realname;
        $upArr['du_zhmyremark'] = $logToMyRemarkStr;
        $upArr['du_zhremarkstr'] = json_encode($logList,true);
        Db::name('ditui_user')->where('dl_id',$nowdl_id)->update($upArr);

        $back['state'] = 'addOk';
        $back['msg'] = '修改成功';
        $back['newLogListArr'] = $logList;
        return $this->renderSuccess('修改成功', '', $back);
    }

    /** 批量上传陌客数据 */
    public function piliAddmoke(){
        $file = $this->request->file('file');
        if($file){
            // 移动文件到指定目录
            $info = $file->move('./uploads/csv');

            if ($info) {
                // 读取 CSV 文件内容
                $filePath = './uploads/csv/' . $info->getSaveName();
                // 检查文件是否存在
                if (!file_exists($filePath)) {
                    return $this->renderError('未找到保存的文件');
                }
                $csvData = $this->readCsvFile($filePath);
                //ddd($csvData);
                //设置批量上传参数
                $inArr = $this->piliangIndb($csvData);
                $back['code'] = 1;
                $back['msg'] = '修改成功';
                $back['csvdata'] = $csvData;
                $back['inArr'] = $inArr;
                echo json_encode($back, true);
            }
            else{
                $back['code'] = 0;
                $back['msg'] = '文件未上传完成';
                echo json_encode($back, true);
            }
        }
        else {
            $back['code'] = 0;
            $back['msg'] = '未接收到文件';
            echo json_encode($back, true);
        }
    }
    private function readCsvFile($filePath){
        $rows = array();
        // 打开文件
        if (($handle = fopen($filePath, 'r')) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                // 将每行数据添加到数组中
                foreach($data as $key => $val){
                    $data[$key] = iconv('gbk','utf-8', $val.'');
                }
                $rows[] = $data;
            }
            // 关闭文件指针
            fclose($handle);
        }
        return $rows;
    }
    private function piliangIndb($csvData){
        $inArr = array();
        foreach($csvData as $key => $val){
            $mobile = trim($val[3]);
            if($mobile!="" && $key>0){
                //检查该手机号是否已经入库
                $isInObj = Db::name('ditui_user')->field('dl_id')->where('du_mobile', $mobile)->find();
                if(!$isInObj) {
                    $perArr['dl_shopid'] = $this->ad_shopid;
                    $perArr['dl_shopname'] = $this->ad_shopname;
                    $perArr['dl_channel'] = '批量导入';
                    $perArr['du_mobile'] = $mobile;
                    $perArr['du_truename'] = trim($val[0]) != '' ? trim($val[0]) : '';
                    $perArr['du_school'] = trim($val[1]) != '' ? trim($val[1]) : '';
                    $perArr['du_grade'] = trim($val[2]) != '' ? trim($val[2]) : '';
                    $perArr['wxapp_id'] = $this->wxapp_id;
                    $perArr['dl_dituiname'] = '导入 (' . $this->admin_realname . ')';
                    $perArr['dl_addtime'] = date('Y-m-d H:i:s', time());
                    $inArr[] = $perArr;
                }
            }
        }
        //ddd($inArr);
        $result = Db::name('ditui_user')->insertAll($inArr);
        return $inArr;
    }
}
